﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using EnumKeys;
using Webapp;
using xundh.Common.Utils.DEncrypt;
namespace xundh.API.Org
{
    /// <summary>
    /// Org_Hards 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]

    public class Org_Hards : BaseService
    {
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Add(int HardsId, string HardStr, string Mem, int DepartId, bool HardState,string Finger)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            HardStr = StringUtil.TBCode(HardStr);
            Mem = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(Mem));

            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            xundh.Model.Org_Hards m;

            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();

            if (HardsId > 0)
            {
                if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "终端管理", "改")) return ServiceStateKeys.NoPermiss;
                m = bll.GetModel(HardsId);
            }
            else
            {
                if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "终端管理", "增")) return ServiceStateKeys.NoPermiss;
                //避免重复
                List<xundh.Model.Org_Hards> ms = bll.GetModelList("HardStr='" + HardStr + "'");
                if (ms.Count > 0)
                {
                    serviceOperation.Logout();
                    if (!ms[0].HardState)
                        return ServiceStateKeys.NoPermiss;
                    else
                    {
                        if (ms[0].Mac != Finger)
                        {
                            ms[0].Mac = Finger;
                            bll.Update(ms[0]);
                        }
                        return ServiceStateKeys.Exists;
                    }
                }
                m = new xundh.Model.Org_Hards();

                m.AddUserId = U.UserId;
                m.AddUser = U.UserName;
                m.AddTime = NOW;
                m.AddIp = IP;
                //生成HardStr
                m.HardStr = HardStr;
                m.Mac = Finger;
            }
            m.LastTime = NOW;
            m.LastIp = IP;
            m.Mem = Mem;
            m.DepartId = DepartId;
            m.HardState = HardState;
            m.Mac = Finger;
            if (HardsId > 0)
                bll.Update(m);
            else
            {
                bll.Add(m);
                serviceOperation.Logout();
            }

            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows)
        {
            if (U == null) return null;
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "终端管理", "查")) return null;

            string DepartId = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["txtDeparts"]));
            string txtHardStr = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["txtHardStr"]));
            string where = "1=1";
            if ((DepartId != "") && (DepartId !="0"))
            {
                if (StringUtil.IsInt(DepartId)) {
                    Org.Org_Departs serviceOrgDeparts = new Org.Org_Departs();
                    string departids = serviceOrgDeparts.GetStringsDepartsAndSons(int.Parse( DepartId));
                    departids = departids.ItemAdd(DepartId);
                    if (departids != "")
                        where += " AND AddDepartId in (" + departids + ")";
                }
                else
                where += String.Format(" AND DepartId in({0})", DepartId);
            }
            if (txtHardStr != "")
                where += String.Format(" AND HardStr Like '%{0}%'", txtHardStr);
            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            JqGridHandler datagrid = new JqGridHandler(where);
            int recordcount = bll.GetRecordCount(datagrid.StrWhere);
            datagrid.init(where, page, recordcount, rows, "", "");
            using (DataSet ds = bll.GetListByPage(datagrid.StrWhere, datagrid.Order, datagrid.StartIndex, datagrid.EndIndex))
            {
                JsonTable jt = new JsonTable(ds.Tables[0], recordcount, datagrid.P, datagrid.Recordcount);
                return jt;
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet=true)]
        public xundh.Model.Org_Hards Query(int id)
        {
            if (U == null) return null;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)Session[EnumKeys.SessionKey.USER];
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "终端管理", "查")) return null;
            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            xundh.Model.Org_Hards m = bll.GetModel(id);
            return m;
        }

        /// <summary>
        /// 验证硬件序列号及验证码，如果正确生成新的验证码，要注意的是：验证成功本方法会同时更新LastLoginIp,LastLoginTime
        /// </summary>
        /// <param name="HardStr"></param>
        /// 
        /// 
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public HardCheck CheckHard(string HardStr, string CheckStr, long Timestamp, int Rand)
        {
            HardCheck hc = new HardCheck();
            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            HardStr = StringUtil.CutBadSqlInfo(HardStr.Trim());
            CheckStr = StringUtil.CutBadSqlInfo(CheckStr.Trim());
            List<xundh.Model.Org_Hards> lists= bll.GetModelList("HardStr='" + HardStr + "'");
            string Finger;
            if (lists.Count > 0)
                Finger = lists[0].Mac;
            else
            {
                hc.modelHard = null;
                hc.jtDeparts = null;
                return hc;
            }
            string check = StringUtil.EncryptMD5NotUnicode(Finger + ";" + HardStr + ";" + Timestamp + ";" + Rand);
            if (check != CheckStr)
            {   
                hc.modelHard = null;
                hc.jtDeparts = null;
                return hc;
            }
            int notEndBranch = StringUtil.GetIntValue(REQUEST["notEndBranch"]);
            /*
             *  HardStr = hex_md5(HardStr + "oasoijfoijwoef309r02").substring(0, 16);
            var d = (new Date()).format("yyyyMMddhh");
            var checkstr = hex_md5(d + "xundh" + HardStr).substring(0, 16);
            checkstr = hex_md5(checkstr + "erp").substring(0, 16);
             * */
            //计算正确值
//#if RELEASE
//            string d = DateTime.Now.ToString("yyyyMMddHH");
//            string checkstr_current = StringUtil.EncryptMD5NotUnicode(d + "xundh" + HardStr).Substring(0, 16);
//            checkstr_current = StringUtil.EncryptMD5NotUnicode(checkstr_current + "erp").Substring(0, 16);

//            if (CheckStr != checkstr_current) {
//                hc.modelHard = null;
//                hc.jtDeparts = null;
//                return hc;
//            }

//            List<xundh.Model.Org_Hards> models = bll.GetModelList(String.Format("HardStr='{0}' AND HardState=1", HardStr));
//#else
            List<xundh.Model.Org_Hards> models = bll.GetModelList("HardState=1");
//#endif

            if (models.Count < 1)
            {
                hc.modelHard = null;
                hc.jtDeparts = null;
                return hc;
            }

            xundh.Model.Org_Hards m = models[0];
            m.LastLoginIp = HttpContext.Current.Request.UserHostAddress;
            m.LastLoginTime = NOW;
            ///获取客户端信息
            HttpBrowserCapabilities b = HttpContext.Current.Request.Browser;
            if (b != null)
            {
                m.Ua = HttpContext.Current.Request.UserAgent;
                m.Browser = b.Type;
                m.Os = b.Platform;
                m.HardType = (CheckAgent() ? HardType.Pad : HardType.PC).ToString();
                m.BrowserVersion = b.Version;
                int height = StringUtil.GetIntValue(HttpContext.Current.Request["ScreenHeight"]);
                int width = StringUtil.GetIntValue(HttpContext.Current.Request["ScreenWidth"]);
                if (height + width > 0)
                {
                    m.ScreenHeight = height;
                    m.ScreenWidth = width;
                }
            }
            bll.Update(m);
            hc.modelHard = m;
            API.Org.Org_Departs serviceOrg = new Org_Departs();
            if (notEndBranch > 0)
                hc.jtDeparts = serviceOrg.GetListsNotEndBranch(); //所有节点
            else
                hc.jtDeparts = serviceOrg.GetListsEndBranch(); //所有终极实体节点
            return hc;
        }

        /// <summary>
        /// 生成新的key
        /// </summary>
        /// <param name="HardStr"></param>
        /// <param name="CheckStr"></param>
        /// <returns></returns>
        public bool Update(xundh.Model.Org_Hards model)
        {
            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            return bll.Update(model);
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public ServiceStateKeys Delete(int id)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.Model.RBAC_Users mUser = (xundh.Model.RBAC_Users)Session[EnumKeys.SessionKey.USER];
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(mUser.UserId, "终端管理", "删")) return ServiceStateKeys.NoPermiss;
            xundh.BLL.Org_Hards bll = new xundh.BLL.Org_Hards();
            bll.Delete(id);
            return ServiceStateKeys.Success;
        }

        /// <summary>
        /// 判断是否是移动客户端
        /// </summary>
        /// <returns></returns>
        private static bool CheckAgent()
        {
            bool flag = false;
            string agent = HttpContext.Current.Request.UserAgent;
            if (agent == null) return false;
            string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
            //排除 Windows 桌面系统            
            if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
            {
                //排除 苹果桌面系统                
                if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
                {
                    foreach (string item in keywords)
                    {
                        if (agent.Contains(item))
                        {
                            flag = true;
                            break;
                        }
                    }
                }
                flag = true;
            }
            return flag;
        }
    }
}

public enum HardType { PC, Pad, Mobile }
public struct HardCheck
{
    public xundh.Model.Org_Hards modelHard;
    public JsonTable jtDeparts;
}